﻿using System.Collections.Generic;
using System.Web;
using umbraco.cms.businesslogic;
using umbraco.DataLayer;

namespace Umb.SimpleWebsite.Shared.Content.BackOffice
{
    /// <summary>
    /// needs to get data about current content in the backoffice
    /// </summary>
    public static class BackOfficeContext
    {

        public static CMSNode CurNode
        {
            get
            {
                int docid;
                if (int.TryParse(HttpContext.Current.Request["id"], out docid))
                {
                    return new CMSNode(docid);
                } return null;
            }
        }
        public static CMSNode ParentNodeByLevel(int level)
        {
            CMSNode result = CurNode;
            while (level < result.Level && result.ParentId > -1)
                result = result.Parent;
            return result;
        }
        public static Site Site
        {
            get
            {
                CMSNode result = CurNode;
                if (result != null)
                {
                    while (result.ParentId > -1) result = result.Parent;
                    if (result != null)
                    {
                        umbraco.cms.businesslogic.Content c = new umbraco.cms.businesslogic.Content(result.Id);
                        return c != null && c.ContentType != null && c.ContentType.Alias.Equals(Aliases.Pages.site, System.StringComparison.InvariantCultureIgnoreCase)
                            ? new Site(result)
                            : null;
                    }
                }
                return null;
            }
        }

        public static CMSNode GetChildOfType(string typeAlias, int startFrom)
        {
            ///sql needs to be optimized
            List<CMSNode> nodes = new List<CMSNode>();
            ISqlHelper Sql= umbraco.BusinessLogic.Application.SqlHelper;
            CMSNode result= null;
            string sqlstr = "Select nt.nodeid [id], tn.alias,cn.text,cn.path from cmsContent nt inner join cmsContentType  tn  on nt.contenttype=tn.nodeid inner join umbraconode cn  on nt.nodeid=cn.id where lower(tn.[alias])='" + typeAlias + "' and cn.path like '%," + startFrom.ToString() + "%'";
            using (IRecordsReader reader = Sql.ExecuteReader(sqlstr,new IParameter[] {Sql.CreateParameter("@alias", typeAlias)}))
            {
                while (reader.Read())
                {
                    result = new umbraco.cms.businesslogic.CMSNode(reader.Get<int>("id"));
                    if (result.ParentId == startFrom) return result;
                    else nodes.Add(result);
                }
            }
            //no exact match
            foreach (CMSNode item in nodes)
            {
                result = GetChildOfType(typeAlias, item.Id);
                if (result != null) return result;
            }
            return null;
        }

            


    }

    
    public class Site
    {
        public CMSNode Data { get; set; }
        private umbraco.cms.businesslogic.Content content;
        public Site(CMSNode innerData)
        {
            Data = innerData;
            if (innerData!=null) content = new umbraco.cms.businesslogic.Content(innerData.Id); 
        }

        public int Id
        {
            get
            {
                return Data.Id;
            }
        }
        
        private CMSNode homePage;
        public CMSNode HomePage
        {
            get
            {
                if (homePage == null)
                    homePage = BackOfficeContext.GetChildOfType(Aliases.Pages.homepage, Id);

                return homePage;
            }
        }


        private CMSNode settings;
        public CMSNode Settings
        {
            get
            {
                if (settings == null)
                    settings = BackOfficeContext.GetChildOfType(Aliases.Pages.settings, Id);

                return settings;
            }
        }

        public string DefaultPageId
        {
            get {
                string propvalue = System.Convert.ToString(GetSiteProperty(Aliases.Properties.site_defaultpage));
                return string.IsNullOrEmpty(propvalue) ? "-1" : propvalue;
            }
        }

        
        
        public object GetSiteProperty(string name)
        {            
            return content.getProperty(name).Value;
        }

    }

    public class Aliases
    {
        public class Pages
        {
            public const string site = "site";
            public const string homepage = "home";
            public const string settings = "settings";
        }
        public class Properties
        {
            public const string site_defaultpage = "homepage";
        }
    }

}